package com.itheima.appserver.service;

import com.aliyuncs.utils.StringUtils;
import com.itheima.appserver.exception.BusinessException;
import com.itheima.autoconfig.template.HuanXinTemplate;
import com.itheima.autoconfig.template.SmsTemplate;
import com.itheima.dubbo.api.UserApi;
import com.itheima.model.domain.User;
import com.itheima.model.vo.ErrorResult;
import com.itheima.utils.Constants;
import com.itheima.utils.JwtUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @DubboReference
    private UserApi userApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;

    public static final String CHECK_CODE = "CHECK_CODE_";

    public void sendMsg(String phone) {
        //生成验证码
//        String code = String.valueOf(ValidateCodeUtils.generateValidateCode(6));
        String code = "123456";
        //发送验证码
        smsTemplate.testsend(phone, code);
        //存储到redis中,设置5分钟
        redisTemplate.opsForValue().set(CHECK_CODE + phone, code, Duration.ofMinutes(5));
    }

    public Map loginVerification(String phone, String verificationCode) {

        //1.获取redis中的验证码进行比较
        String code = (String) redisTemplate.opsForValue().get(CHECK_CODE + phone);
        //2.判断用户验证码和缓存中的验证码是否正确
        if (StringUtils.isEmpty(verificationCode) || !code.equals(verificationCode)) {
            throw new BusinessException(ErrorResult.loginError());
        }
        //3.删除缓存
        redisTemplate.delete(CHECK_CODE + phone);
        //4.通过手机查询用户
        User user = userApi.findByMobile(phone);
        //判断新老用户的标记
        boolean isNew = false;
        //判断用户是否为空
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long id = userApi.save(user);
            user.setId(id);
            isNew = true;
            //生成环信用户
            extracted(user);
        }
        extracted(user);

        //6、通过JWT生成token(存入id和手机号码)
        Map tokenMap = new HashMap();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", phone);
        String token = JwtUtils.getToken(tokenMap);
        //7、构造返回值
        Map retMap = new HashMap();
        retMap.put("token", token);
        retMap.put("isNew", isNew);

        return retMap;
    }

    private void extracted(User user) {
        String hxUser = "hx" + user.getId();
        Boolean result = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
        if (result) {
            user.setHxUser(hxUser);
            user.setHxPassword(Constants.INIT_PASSWORD);
            userApi.update(user);
        }
    }
}
